﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using R.FarmSmartSleep.RBAC.API.Common.R.Dtos;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command.Permissions
{
    public class PermissionCascaderHandler : IRequestHandler<PermissionCascaderCommon, ResultT<List<PermissionCascaderDto>>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly IMapper mapper;
        public PermissionCascaderHandler(IBaseRepository<Permission> _permissionRep, IMapper _mapper)
        {
            permissionRep = _permissionRep;
            mapper = _mapper;
        }
        public async Task<ResultT<List<PermissionCascaderDto>>> Handle(PermissionCascaderCommon request, CancellationToken cancellationToken)
        {
            var result = new ResultT<List<PermissionCascaderDto>>() { Code = (int)CodeEnum.search };
            var list = await permissionRep.GetAll().Where(c => c.PerantId == 0).ToListAsync();
            List<PermissionCascaderDto> permissionCascaderDtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascaderDto = new PermissionCascaderDto();
                permissionCascaderDto.label = item.PermissionsName;
                permissionCascaderDto.value = item.PermissionsId;
                permissionCascaderDto.children = Cascader(item.PermissionsId);
                permissionCascaderDtos.Add(permissionCascaderDto);
            }
            result.Item = permissionCascaderDtos;
            return result;
        }
        public List<PermissionCascaderDto> Cascader(int parentId)
        {
            var list = permissionRep.GetAll().Where(c => c.PerantId == parentId).ToList();
            List<PermissionCascaderDto> permissionCascaderDtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascaderDto = new PermissionCascaderDto();
                permissionCascaderDto.label = item.PermissionsName;
                permissionCascaderDto.value = item.PermissionsId;
                permissionCascaderDto.children = Cascader(item.PermissionsId);
                permissionCascaderDtos.Add(permissionCascaderDto);
            }

            return permissionCascaderDtos;
        }
    }
}
